class FileHandler {
    constructor(chatManager) {
        this.chatManager = chatManager;
        this.uploadInProgress = false;
        this.fileList = new Set();
        
        this.initializeFileHandlers();
    }

    initializeFileHandlers() {
        const fileInput = document.getElementById('file-input');
        const uploadBtn = document.getElementById('upload-btn');

        fileInput.addEventListener('change', () => {
            uploadBtn.disabled = !fileInput.files.length;
        });

        this.updateFileList();
        setInterval(() => this.updateFileList(), 5000);
    }

    async uploadFile() {
        if (this.uploadInProgress) return;

        const fileInput = document.getElementById('file-input');
        const file = fileInput.files[0];
        
        if (!file) return;

        this.uploadInProgress = true;
        const uploadBtn = document.getElementById('upload-btn');
        const progressBar = document.getElementById('upload-progress');
        const progressValue = document.getElementById('progress-value');
        
        uploadBtn.disabled = true;
        progressBar.style.display = 'block';
        
        const formData = new FormData();
        formData.append('file', file);
        formData.append('username', this.chatManager.username);

        try {
            const xhr = new XMLHttpRequest();
            xhr.open('POST', `${this.chatManager.currentServer}/upload_file`, true);

            xhr.upload.onprogress = (e) => {
                if (e.lengthComputable) {
                    const percentComplete = (e.loaded / e.total) * 100;
                    progressValue.style.width = percentComplete + '%';
                }
            };

            xhr.onload = () => {
                if (xhr.status === 200) {
                    fileInput.value = '';
                    this.chatManager.updateMessages();
                    this.updateFileList();
                } else {
                    alert('上传失败');
                }
                this.resetUploadState();
            };

            xhr.onerror = () => {
                alert('上传失败');
                this.resetUploadState();
            };

            xhr.send(formData);
        } catch (error) {
            console.error('文件上传失败:', error);
            this.resetUploadState();
        }
    }

    resetUploadState() {
        this.uploadInProgress = false;
        document.getElementById('upload-btn').disabled = true;
        document.getElementById('upload-progress').style.display = 'none';
        document.getElementById('progress-value').style.width = '0';
    }

    async updateFileList() {
        try {
            const response = await fetch(`${this.chatManager.currentServer}/get_messages`);
            const data = await response.json();
            const fileMessages = data.messages.filter(msg => msg.is_file);
            
            const fileListElement = document.getElementById('file-list');
            fileListElement.innerHTML = '';
            
            fileMessages.forEach(msg => {
                if (!this.fileList.has(msg.filename)) {
                    this.fileList.add(msg.filename);
                    const fileItem = this.createFileItem(msg);
                    fileListElement.appendChild(fileItem);
                }
            });
        } catch (error) {
            console.error('更新文件列表失败:', error);
        }
    }

    createFileItem(msg) {
        const fileItem = document.createElement('div');
        fileItem.className = 'file-item';
        fileItem.innerHTML = `
            <div class="file-icon">📄</div>
            <div class="file-info">
                <div class="file-name">${msg.filename}</div>
                <div class="file-meta">${msg.username} - ${msg.timestamp}</div>
            </div>
            <div class="file-actions">
                <button class="btn" onclick="fileHandler.downloadFile('${msg.filename}')">
                    下载
                </button>
            </div>
        `;
        return fileItem;
    }

    downloadFile(filename) {
        const link = document.createElement('a');
        link.href = `${this.chatManager.currentServer}/download_file/${filename}`;
        link.download = filename;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
    }
}

// 初始化文件处理器
const fileHandler = new FileHandler(chatManager); 